<template>
  <div>
    <el-card>
      <el-row :gutter="15">
        <el-col :span="visibleL ? 5 : 0" v-if="visibleL" style="overflow: auto;">
          <el-card class="leftBox" shadow="never" :body-style="{padding: '0px'}" style="overflow-y: auto;">
            <el-collapse v-model="activeName" accordion>
              <el-collapse-item title="广告节目单" name="1">
                <div class="selectArea">
                  <el-tree
                    accordion
                    ref="treeone"
                    :data="optionsType"
                    :expand-on-click-node="false"
                    node-key="value"
                    :default-expanded-keys="defaultKeys"
                    :props="{ children: 'children' }"
                    @node-click="handleTypeClick">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span v-if="node.level === 3 " style="position: relative;">
                        <i v-if="data.status === 1" class="el-icon-success" style="color: rgb(37 74 156);left: -20px;top:-7px;position: absolute;"></i>
                        <i v-else class="el-icon-edit" style="color: rgb(156 14 14);left: -20px;top:-7px;position: absolute;"></i>
                      </span>
                      <span :title="node.label" style="margin-right: 30px; width: 62%;text-overflow: ellipsis;overflow: hidden;">
                        <font v-if="node.level === 3" style="color: rgb(35 55 132); font-weight: bold;">{{ node.label }} </font>
                        <font v-else>{{ node.label }}</font>
                      </span>
                      <transition name="el-fade-in">
                        <span v-if="(node.key !== 0 && node.key === pgmgrpCurr.value)">
                          <el-button
                            v-if="node.level === 2"
                            icon="el-icon-plus"
                            style="color: #fff;"
                            type="text"
                            size="mini"
                            title="新增"
                            v-permission="permission.add"
                            @click="dialogInfo.cu = 1">
                          </el-button>
                          <el-button
                            v-if="node.level === 3"
                            icon="el-icon-delete"
                            style="color: #fff;"
                            type="text"
                            size="mini"
                            title="删除"
                            @click="deletePgmgrp"
                            v-permission="permission.del">
                          </el-button>
                      </span>
                      </transition>
                    </span>
                  </el-tree>
                </div>
              </el-collapse-item>
            </el-collapse>
            <el-dialog
              :title="dialogInfo.title"
              :before-close="cancelCU"
              :visible.sync="dialogInfo.cu > 0"
              width="420px"
              :close-on-click-modal="false">
              <el-form :model="pgmgrpform" ref="pgmgrpformRef" label-width="120px">
                <el-form-item label="节目单名称" prop="play_date">
                  <div class="elInputS">
                    <el-date-picker v-model="pgmgrpform.play_date" :picker-options="expireTimeOption" style="width: 220px;" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                  </div>
                </el-form-item>
                <el-form-item label="从其他日期导入" prop="other_date">
                  <div class="elInputS">
                    <el-select v-model="pgmgrpform.other_date" placeholder="请选择节目日期" style="width: 220px;" @change="getOtherAdvSeq()">
                      <el-option v-for="(item, index) in other_data_arr" :label="item.play_date" :value="item.pl_id" :key="index"></el-option>
                    </el-select>
                  </div>
                </el-form-item>
                <el-form-item label="请选择节目时段" prop="advseqs">
                  <div class="elInputS">
                    <el-select v-model="pgmgrpform.advseqs" placeholder="请选择节目时段" style="width: 220px;">
                      <el-option value="all" label="全部"></el-option>
                      <el-option v-for="(item, index) in other_advseqlist" :label="item.s_time + ' - ' + item.adv_seg_name" :value="item.adv_seq_id" :key="index"></el-option>
                    </el-select>
                  </div>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="text" @click="cancelCU">取消</el-button>
                <el-button :loading="dialogInfo.cu === 4" type="primary" @click="submitCU">确认</el-button>
              </div>
            </el-dialog>
          </el-card>
        </el-col>
        <el-col :span="visibleL ? 19 : 24" style="overflow-x: auto;position: relative;padding-left:11px;">
          <span class="animat" style="position: absolute; left: -3px;top: 45%;" @click="visibleL = !visibleL">
            <el-link :underline="false">
              <i class="el-icon-d-arrow-left" v-if="visibleL"></i>
              <i class="el-icon-d-arrow-right" v-else></i>
            </el-link>
          </span>
          <el-row :gutter="20" style="box-shadow: none !important;">
            <el-col :span="18">
              <el-select v-model="advseq" placeholder="请选择节目时段" style="width: 260px;margin-right:10px;" @change="getadvpgmLists()">
                <el-option value="all" label="全部"></el-option>
                <el-option v-for="(item, index) in advseqlist" :class="item.a_class"  :label="item.s_time + ' - ' + item.adv_seg_name" :value="item.adv_seq_id" :key="index"></el-option>
              </el-select>
              <el-button
                type="primary"
                v-permission="permission.add"
                icon="el-icon-plus"
                @click="innermatdialogVisible = true"
                :disabled="pgmgrpnode === null">素材库</el-button>
              <el-button
                type=""
                v-permission="permission.add"
                icon="el-icon-plus"
                @click="innerdialogVisible = true"
                :disabled="pgmgrpnode === null">广告库</el-button>
              <el-button type="success" @click="ReviewDetail" :disabled="pgmgrpnode === null" v-permission="permission.add" icon="el-icon-check">审核</el-button>
              <el-button type="info" @click="historyData" v-permission="permission.add" icon="el-icon-reading">历史数据</el-button>
              <el-button type="danger" @click="delgrpDetail" v-permission="permission.del" icon="el-icon-delete">删除</el-button>
              <el-button type="success" icon="el-icon-check" v-if="grplistSave !== false" @click="addgrpoupmats">保存</el-button>
              <!-- 封装的素材弹窗组件 prop:
                :innerVisible  // 控制弹窗隐藏显示
                v-model        // 接收返回的素材对象
                @change        // 选中素材改变点击确定后的回调事件.
                @close         // 弹窗点击关闭的回调事件，用于告知父组件，由父控制关闭或显示
              -->
              <mat-dialog
                :innerVisible="innermatdialogVisible"
                v-model="matSelectRows"
                mattype="adv"
                :multify="true"
                :drawerShow="true"
                @change="matSelectChange"
                @close="listenMatClose"
                @dragchange="dragAcceptRows">
              </mat-dialog>
              <!-- 封装的广告库弹窗组件 prop:
                :innerVisible  // 控制弹窗隐藏显示
                v-model        // 接收返回的素材对象
                @change        // 选中素材改变点击确定后的回调事件.
                @close         // 弹窗点击关闭的回调事件，用于告知父组件，由父控制关闭或显示
              -->
              <advlib-dialog
                :innerVisible="innerdialogVisible"
                v-model="advSelectRows"
                :multify="true"
                :drawerPgmShow="true"
                @change="advSelectChange"
                @close="listenClose"
                @dragchange="dragPgmAcceptRows">
              </advlib-dialog>
            </el-col>
            <el-col :span="6" style="float: right; text-align: right;">
              <table-tools
                :drawerSearch="drawerVisible"
                @searchchange="searchChange"
                @refreshclick="refreshClick">
              </table-tools>
            </el-col>
            <el-col :span="8" style="margin:8px 0 0;">
              <span >时段：[{{wordss.title}}] {{wordss.time}}</span>
              <span style="margin-left:20px">长度：{{wordss.total_time}}</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <!-- 列表区域 -->
              <el-table
                @selection-change="handleSelectionChange"
                row-key="id"
                v-loading="loading"
                height="75vh"
                ref="table"
                highlight-current-row
                :data="matlists"
                @row-contextmenu="mouseRightUp"
                lazy
                border
                style="width: 100%;"
                :row-class-name="manyadvseq">
                <el-table-column :selectable="checkboxT" type="selection" width="55" />
                <el-table-column type="index" label="序号" width="60px" sortable="custom"></el-table-column>
                <el-table-column prop="adv_seg_name" label="时段" show-overflow-tooltip></el-table-column>
                <el-table-column prop="play_order" label="顺序" width="50px" show-overflow-tooltip></el-table-column>
                <el-table-column prop="pgm_id" label="节目代码" width="90px" show-overflow-tooltip></el-table-column>
                <el-table-column prop="pgm_name" label="节目名称" show-overflow-tooltip></el-table-column>
                <el-table-column prop="mat_type_name" label="节目类型" width="105px" show-overflow-tooltip></el-table-column>
                <el-table-column prop="pgm_len" label="节目长度" width="95px" show-overflow-tooltip>
                  <template v-slot="scope">
                    <time-picker inputType="readonly" v-model="scope.row.pgm_len" />
                  </template>
                </el-table-column>
                <el-table-column prop="mat_id" label="素材ID" width="90px" show-overflow-tooltip></el-table-column>
                <el-table-column prop="markin" label="入点" width="95px" show-overflow-tooltip>
                  <template v-slot="scope">
                    <time-picker inputType="readonly" v-model="scope.row.markin" />
                  </template>
                </el-table-column>
                <el-table-column prop="markout" label="出点" width="95px" show-overflow-tooltip>
                  <template v-slot="scope">
                    <time-picker inputType="readonly" v-model="scope.row.markout" />
                  </template>
                </el-table-column>
                <el-table-column prop="create_time" label="素材创建时间" width="140px" show-overflow-tooltip></el-table-column>
                <el-table-column prop="ext_only_id" label="素材状态" width="70px"></el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-dialog
            append-to-body
            :close-on-click-modal="false"
            :before-close="handlecancelCU"
            :visible.sync="playDialog.status === 1"
            title="审核与反审"
            width="380px">
            <el-form ref="reviewform" inline :model="reviewform" label-width="85px">
              <el-form-item label="审核意见" prop="review_word">
                 <el-input type="textarea" rows="5" v-model="reviewform.review_word"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" :disabled="pgmgrpCurr.status === 1" @click="handlesubmitCU">审核通过</el-button>
              <el-button type="danger" :disabled="pgmgrpCurr.status === 0" @click="handlesubmitNO">不通过</el-button>
              <el-button type="brand" @click="handlecancelCU">取消</el-button>
            </div>
          </el-dialog>
          <el-dropdown @command="handleCommand" trigger="click" id="floatmousebox" ref="dropmenu" placement="bottom-start">
            <span class="el-dropdown-link"></span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="top" icon="el-icon-top">上移</el-dropdown-item>
              <el-dropdown-item command="down" icon="el-icon-bottom">下移</el-dropdown-item>
              <el-dropdown-item command="copy" icon="el-icon-document-copy">复制</el-dropdown-item>
              <el-dropdown-item command="paste" icon="el-icon-document-checked">粘贴</el-dropdown-item>
              <el-dropdown-item command="total" icon="el-icon-s-data">统计</el-dropdown-item>
              <el-dropdown-item command="del" icon="el-icon-delete">多重删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import commonMethods from '@/utils/commonMethods.js'
import { pgmInfoConfig } from '@/sysconfig.js' //* 引入节目库系统配置
import { lists, add, del, channelGroup, channelGroupAdd, channelGroupEdit, channelGroupDel } from '@/api/advpgmlist/advgroup.js' // 频道列表接口

// 引入已封装好的增删改查相关组件
import tableTools from '@/components/tableToolsComponents' // tabs工具栏组件
import MatDialog from '@/components/MatdialogComponents.vue' // 素材列表弹窗组件
import AdvlibDialog from '@/components/AdvlibdialogComponents.vue' // 广告库列表弹窗组件

export default {
  name: 'advpgmlist',
  mixins: [commonMethods],
  components: { tableTools, MatDialog, AdvlibDialog },
  provide() {
    return {
      editroom: this
    }
  },
  filters: {
    subTimeDate: function(value) {
      if (value !== null && value.length > 10) {
        return value.substr(0, 10)
      }
      return value
    }
  },
  watch: {
    'dialogInfo.cu' (newValue, oldValue) {
      if (newValue === 1) {
        this.dialogInfo.title = '新增广告节目单'
        this.pgmgrpform = {}
        this.pgmgrpform.channel_id = this.pgmgrpCurr.value
      } else if (newValue === 3) {
        this.dialogInfo.title = '复制广告节目单'
        this.$set(this.pgmgrpform, 'play_date', this.pgmgrpCurr.label)
        this.pgmgrpform.channel_id = this.pgmgrpCurr.pid
      }
    },
    'matlists' () {
      this.grplistSave = true
    },
    'pgmgrpnode' (newValue, oldValue) {
      if (newValue === null) return
      this.getgrpDetail()
    }
  },
  data() {
    return {
      visibleL: true,
      /* 设置页面权限 */
      permission: {
        add: ['admin', 'advpgmlist::add'],
        edit: ['admin', 'advpgmlist::edit'],
        del: ['admin', 'advpgmlist::del']
      },
      rules: {}, // 表单验证规则
      activeName: '1',
      optionsType: [
        {
          label: '广告节目单',
          value: 0,
          children: []
        }
      ],
      queryInfo: {}, // 列表查询参数
      loading: false,
      drawerVisible: true,
      grplistSave: false, // 列表变化状态保存按钮置为disabled
      pgmInfoConfig, // 节目库系统配置
      channelList: [], // 频道列表
      advseqlist: [], // 节目时段列表
      advseq: [], // 节目时段列表
      t_type: '',
      rowscurrent: null,
      innerdialogVisible: false,
      innermatdialogVisible: false,
      matSelectRows: null,
      advSelectRows: null,
      dialogInfo: {
        title: '新增广告节目单信息',
        cu: 0
      },
      playDialog: {
        status: 0
      },
      handleCheckboxRows: [],
      matlists: [],
      pgmgrpnode: null,
      pgmgrpCurr: {},
      pgmgrpform: {},
      defaultKeys: [0],
      handleCurrentRow: {}, // 当前单选选中的rows对象
      dragInsetIndex: undefined, // 拖拽目标键值
      dragInsetadvseq: undefined, // 拖拽目标时段ID
      dragInsetadvseqName: undefined, // 拖拽目标时段名称
      table_sort: true,
      mouseX: '',
      mouseY: '',
      reviewform: [],
      expireTimeOption: {
        disabledDate(date) {
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      },
      other_data_arr: [],
      other_advseqlist: [],
      wordss: {
        title: '-',
        time: '--:--:--:--',
        total_time: '--:--:--:--'
      },
      CopyIndex: null
    }
  },
  async created() {
    document.oncontextmenu = function (event) {
      //* 阻止页面浏览器右键菜单事件
      event.preventDefault()
    }
    // 获取节目类型菜单
    this.getmatTypeList()
    this.advseq = 'all'
    this.table_sort = true
  },
  mounted() {
    this.setSort()
  },
  async beforeRouteLeave(to, from, next) {
    if (this.grplistSave) {
      const confirmresult = await this.$confirm('列表已修改现在要保存吗？', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        next()
      }
      this.addgrpoupmats()
      // 是的话 则保存后弹出保存成功提示再确定离开页面。
      next()
    }
    next()
  },
  methods: {
    // 错误提示跟随鼠标
    errorMessage(msg) {
      this.$message({ message: msg, type: 'error', duration: 900 })
      const dom = document.getElementsByClassName('el-message--error')
      dom[0].style.left = this.mouseX + 'px'
      dom[0].style.top = this.mouseY + 'px'
    },
    //* 获取节目单素材列表
    async getAdvSeqList(channel_id, play_date) {
      const { data: res } = await this.$http.get('advpgmlist/getadvseqlist', {
        params: { channel: channel_id, play_date: play_date }
      })
      if (res.meta.status !== 200) {
        return this.errorMessage('获取频道列表失败！')
      }
      this.advseqlist = res.data.list
    },
    //* 获取历史节目单以供复制
    async getOtherAdvList(channel_id) {
      const { data: res } = await this.$http.post('advpgmlist/getOtherAdvList', {
        channel_id: channel_id
      })
      if (res.meta.status !== 200) {
        return this.errorMessage('获取节目单列表失败！')
      }
      this.other_data_arr = res.data.list
    },
    //* 获取历史节目单的节目时段列表
    async getOtherAdvSeq() {
      //* 获取节目时段
      const { data: res } = await this.$http.post('advpgmlist/getOtherAdvSeq', {
        pl_id: this.pgmgrpform.other_date
      })
      if (res.meta.status !== 200) {
        return this.errorMessage('获取节目时段列表失败！')
      }
      this.other_advseqlist = res.data.list
    },
    //* 获取节目时段列表
    getadvpgmLists() {
      //* 获取节目时段
      this.getAdvSeqList(this.pgmgrpCurr.pid, this.pgmgrpCurr.play_d)
      this.getgrpDetail()
      //* 获取该时段的详情
    },
    // 多个时段显示颜色控制
    manyadvseq({ row }) {
      if (!row.s_status) {
        return 'another-row'
      }
      return ''
    },
    // 当表格单元行被鼠标右键点击时触发事件
    mouseRightUp(row, column, event) {
      this.$refs.dropmenu.visible = false
      this.$refs.table.setCurrentRow(row) // 用于单选表格，设定单元行为选中行
      this.mouseX = event.clientX
      this.mouseY = event.clientY
      // 设定操作栏浮窗相对页面位置,并显示ss。
      const dom = document.getElementById('floatmousebox')
      dom.style.left = event.clientX + 20 + 'px'
      dom.style.top = event.clientY + 'px'
      this.$refs.dropmenu.show()
      this.handleCurrentRow = row // 缓存当前右键选中行
    },
    // 列表操作栏下拉菜单指令触发方法
    handleCommand(commond) {
      switch (commond) {
        case 'top':
          this.TopAdvpgm(this.handleCurrentRow)
          break
        case 'down':
          this.DownAdvpgm(this.handleCurrentRow)
          break
        case 'copy':
          this.copyAdvpgm(this.handleCurrentRow)
          break
        case 'paste':
          this.pasteAdvpgm(this.handleCurrentRow)
          break
        case 'total':
          this.TotalAdvpgm(this.handleCurrentRow)
          break
        case 'del':
          this.delMoreAdvpgm(this.handleCurrentRow)
          break
      }
    },
    //* 上移节目单素材
    TopAdvpgm(row) {
      if (row.play_order === 1) {
        return this.errorMessage('该节目单已处在第一位，不能上移！')
      }
      this.grplistSave = true
      var tarIndex
      // this.matlists.splice(evt.newIndex, 0, targetRow)
      this.matlists.forEach((item, index) => {
        if (row.id === item.id) {
          tarIndex = index
        }
      })
      // 比较是否跨时段，如果跨时段则报错误提示
      if (this.matlists[tarIndex - 1].advseg_id !== row.advseg_id) {
        return this.errorMessage('请不要跨时段移动节目素材！')
      }

      // 交叉两个素材的排序
      this.matlists[tarIndex - 1].play_order = row.play_order
      this.matlists[tarIndex].play_order = row.play_order - 1

      const targetRow = this.matlists.splice(tarIndex, 1)[0]
      this.matlists.splice(tarIndex - 1, 0, targetRow)
    },
    //* 下移节目单素材
    DownAdvpgm(row) {
      this.grplistSave = true
      var tarIndex
      // this.matlists.splice(evt.newIndex, 0, targetRow)
      this.matlists.forEach((item, index) => {
        if (row.id === item.id) {
          tarIndex = index
        }
      })
      // 比较是否跨时段，如果跨时段则报错误提示
      if (this.matlists[tarIndex + 1].advseg_id !== row.advseg_id) {
        return this.errorMessage('请不要跨时段移动节目素材！')
      }

      // 交叉两个素材的排序
      this.matlists[tarIndex + 1].play_order = row.play_order
      this.matlists[tarIndex].play_order = row.play_order + 1

      const targetRow = this.matlists.splice(tarIndex, 1)[0]
      this.matlists.splice(tarIndex + 1, 0, targetRow)
    },
    //* 复制节目单素材
    copyAdvpgm(row) {
      this.matlists.forEach((item, index) => {
        if (row.id === item.id) {
          this.CopyIndex = index
        }
      })
      return this.$message.success('复制成功，请指定位置粘贴！')
    },
    //* 粘贴节目单素材
    pasteAdvpgm(row) {
      if (this.CopyIndex === null) {
        return this.errorMessage('暂未复制素材！')
      }
      this.grplistSave = true
      var ThisIndex
      this.matlists.forEach((item, index) => {
        if (row.id === item.id) {
          ThisIndex = index
        }
      })
      // 改变两个素材的排序
      const copy_news = {
        pl_id: this.matlists[this.CopyIndex].pl_id,
        pgm_id: this.matlists[this.CopyIndex].pgm_id,
        pgm_name: this.matlists[this.CopyIndex].pgm_name,
        pgm_len: this.matlists[this.CopyIndex].pgm_len,
        pgm_type: this.matlists[this.CopyIndex].pgm_type,
        mat_id: this.matlists[this.CopyIndex].mat_id,
        markin: this.matlists[this.CopyIndex].markin,
        markout: this.matlists[this.CopyIndex].markout,
        ext_only_id: this.matlists[this.CopyIndex].ext_only_id,
        create_time: this.matlists[this.CopyIndex].create_time,
        adv_seg_name: row.adv_seg_name,
        play_order: row.play_order,
        adv_seq_id: row.adv_seq_id,
        advseg_id: row.advseg_id
      }
      this.matlists[ThisIndex].play_order = row.play_order + 1
      this.matlists.splice(ThisIndex, 0, copy_news)
    },
    //* 统计节目单素材
    async TotalAdvpgm(row) {
      const { data: res } = await this.$http.post('advpgmlist/TotalAdvpgm', {
        id: row.id
      })
      if (res.meta.status !== 200) {
        return this.errorMessage('统计节目单内容失败！')
      }
      this.$alert('<span>该节目<strong>"' + row.pgm_name + '" </strong>在节目单中一共安排了<strong> ' + res.data + ' </strong>次播出</span>', '素材统计', {
        dangerouslyUseHTMLString: true
      })
    },
    //* 多重删除节目单素材
    async delMoreAdvpgm(row) {
      const confirmresult = await this.$confirm('是否删除当前选中广告节目单`' + this.pgmgrpCurr.label + '` 下节目信息 ，是否确定？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('您已取消了删除')
      }
      const { data: res } = await this.$http.post('advpgmlist/delMoreAdvpgm', {
        advseg_id: row.advseg_id, pl_id: row.pl_id, id: row.id
      })
      if (res.meta.status !== 200) {
        return this.errorMessage('多重删除节目单内容失败！')
      }
      this.getgrpDetail()
    },
    //* 拖拽排序
    setSort() {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = new Sortable(el, {
        group: {
          name: 'shared',
          pull: false
        },
        sort: false, // 不允许组内排序，
        disabled: false, // 允许从其他表格拖拽进组
        animation: 150,
        ghostClass: 'sortable-ghost',
        onEnd: evt => {

        },
        onAdd: (evt) => {
          this.dragInsetIndex = evt.newIndex
          evt.item.remove()
        }
      })
    },
    getmatTypeList() {
      channelGroup().then(res => {
        if (res.status !== 200) {
          console.log('频道分组获取失败')
        }
        this.optionsType[0].children = res.data.data
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== false
    },
    // 监听列表工具栏 刷新点击事件
    refreshClick() {
      // window.location.reload()
      this.getgrpDetail()
    },
    // 监听列表工具搜索change事件
    searchChange(val) {
      this.drawerVisible = val
    },
    // 按广告节目单查看
    async handleTypeClick(data, node, el) {
      if (this.grplistSave) {
        const confirmresult = await this.$confirm('列表已修改现在要保存吗？', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).catch(err => err)
        if (confirmresult === 'confirm') {
          this.addgrpoupmats()
        }
      }
      if (this.$refs.treeone.currentNode !== null) {
        this.$refs.treeone.currentNode.$el.setAttribute('class', 'el-tree-node')
      }
      el.$el.setAttribute('class', 'el-tree-node is-current is-focusable') // 设置选中
      /*      if (data.mat_type_id === undefined) {
        this.query.type = 'all'
      } else {
        this.query.type = this.findNodeChildValArr(data, 'mat_type_id', []).join(',')
      } */
      this.pgmgrpnode = node.level === 3 ? node : null
      this.pgmgrpCurr = data
      if (node.level === 3) {
        this.pgmgrpCurr.pid = node.parent.key
        //* 获取广告节目单的时间
        this.pgmgrpCurr.play_d = node.level === 3 ? node.label : null
        //* 获取节目时段
        this.getAdvSeqList(this.pgmgrpCurr.pid, this.pgmgrpCurr.play_d)
      }
      if (node.level === 2) {
        //* 获取该频道下面的历史节目单以供复制
        this.getOtherAdvList(node.key)
      }
    },
    listenClose(state) {
      this.innerdialogVisible = state
    },
    listenMatClose(state) {
      this.innermatdialogVisible = state
    },
    //* 素材列表弹窗单元行选中返回事件
    matSelectChange(val) {
      if (val !== null && val.length > 0) {
        val.map((item, index) => {
          this.matlists.push({
            pl_id: this.pgmgrpnode.key,
            mat_id: item.mat_id,
            pgm_id: null,
            pgm_name: item.mat_name,
            pgm_len: item.file_len,
            markin: item.markin,
            markout: item.markout,
            advseg_id: this.advseq,
            play_order: index + 1,
            pgm_type: item.mat_type,
            ext_only_id: null
          })
        })
      }
    },
    //* 素材列表弹窗单元行选中返回事件
    dragAcceptRows(sourceRow) {
      if (this.dragInsetIndex === undefined || this.dragInsetIndex === null) return

      const targetRow = {}
      targetRow.s_status = this.dragInsetIndex === 0 ? 1 : this.matlists[this.dragInsetIndex].s_status
      targetRow.pl_id = this.pgmgrpnode.key
      targetRow.mat_id = sourceRow.mat_id
      targetRow.pgm_id = null
      targetRow.pgm_name = sourceRow.mat_name
      targetRow.pgm_len = sourceRow.file_len
      targetRow.markin = sourceRow.markin
      targetRow.markout = sourceRow.markout
      targetRow.advseg_id = this.advseq
      targetRow.play_order = this.dragInsetIndex === 0 ? 1 : this.matlists[this.dragInsetIndex].play_order
      targetRow.pgm_type = sourceRow.mat_type
      targetRow.ext_only_id = null
      targetRow.advseg_id = this.dragInsetIndex === 0 ? this.advseq : this.matlists[this.dragInsetIndex].advseg_id
      targetRow.adv_seg_name = this.dragInsetIndex === 0 ? '' : this.matlists[this.dragInsetIndex].adv_seg_name
      // 插入拖拽节点下标位置
      this.matlists.splice(this.dragInsetIndex, 0, targetRow)
      this.dragInsetIndex = undefined // 关闭事件
    },
    //* 广告库弹窗单元行选中返回事件
    dragPgmAcceptRows(sourceRow) {
      if (this.dragInsetIndex === undefined || this.dragInsetIndex === null) return

      const targetRow = {}
      targetRow.s_status = this.dragInsetIndex === 0 ? 1 : this.matlists[this.dragInsetIndex].s_status
      targetRow.pl_id = this.pgmgrpnode.key
      targetRow.mat_id = sourceRow.mat_id
      targetRow.pgm_id = sourceRow.pgm_id
      targetRow.pgm_name = sourceRow.pgm_name
      targetRow.pgm_len = sourceRow.pgm_len
      targetRow.markin = sourceRow.markin
      targetRow.markout = sourceRow.markout
      targetRow.advseg_id = this.advseq
      targetRow.play_order = this.dragInsetIndex === 0 ? 1 : this.matlists[this.dragInsetIndex].play_order
      targetRow.pgm_type = sourceRow.pgm_type
      targetRow.ext_only_id = null
      targetRow.advseg_id = this.dragInsetIndex === 0 ? this.advseq : this.matlists[this.dragInsetIndex].advseg_id
      targetRow.adv_seg_name = this.dragInsetIndex === 0 ? '' : this.matlists[this.dragInsetIndex].adv_seg_name
      // 插入拖拽节点下标位置
      this.matlists.splice(this.dragInsetIndex, 0, targetRow)
      this.dragInsetIndex = undefined // 关闭事件
      this.table_sort = true // 关闭表格拖拽
    },
    //* 广告库列表弹窗单元行选中返回事件
    advSelectChange(val) {
      if (val !== null && val.length > 0) {
        val.map((item, index) => {
          this.matlists.push({
            pl_id: this.pgmgrpnode.key,
            mat_id: item.mat_id,
            pgm_id: item.pgm_id,
            pgm_name: item.pgm_name,
            pgm_len: item.pgm_len,
            markin: item.markin,
            markout: item.markout,
            advseg_id: this.advseq,
            play_order: index + 1,
            pgm_type: item.pgm_type,
            ext_only_id: null
          })
        })
      }
    },
    getgrpDetail() {
      // 查询广告节目单下素材列表信息
      this.loading = true
      this.queryInfo.type = this.pgmgrpnode.key
      this.queryInfo.advseq = this.advseq
      lists(this.queryInfo).then(res => {
        setTimeout(() => {
          this.loading = false
          if (res.status !== 200) return
          this.matlists = res.data.data.list
          this.grplistSave = false
          this.$nextTick(() => {
            this.grplistSave = false
          })
          //* 获取节目单总时长
          if (this.advseq === 'all') {
            this.wordss.title = '全天'
          } else {
            this.wordss.title = res.data.data.title
          }
          this.wordss.time = res.data.data.time
          this.wordss.total_time = res.data.data.total_time
        }, 150)
      })
    },
    // 向广告节目单下添加素材
    addgrpoupmats() {
      if (this.matlists.length < 1) return
      const matid_str = this.matlists
      // console.log(matid_str)

      const data = {
        pl_id: matid_str
      }
      add(data).then(res => {
        if (res.status !== 200) return
        this.grplistSave = false
        this.$notify({
          title: '保存成功',
          message: '广告节目单素材添加成功！',
          type: 'success'
        })
        this.getgrpDetail()
      })
    },
    // 取消
    cancelCU() {
      this.dialogInfo.cu = 0
      this.pgmgrpform = {}
    },
    //* 新增广告日期单
    submitCU() {
      if (this.dialogInfo.cu === 1 || this.dialogInfo.cu === 3) { // 新增, 复制
        channelGroupAdd(this.pgmgrpform).then(res => {
          if (res.status === 200) {
            this.getmatTypeList()
            this.$message.success('新增成功')
            this.defaultKeys = [this.pgmgrpform.channel_id]
          }
          this.dialogInfo.cu = 0
        })
      } else {
        channelGroupEdit(this.pgmgrpform).then(res => {
          if (res.status === 200) {
            this.getmatTypeList()
            this.$message.success('编辑成功')
            this.defaultKeys = [this.pgmgrpform.pl_id]
          }
          this.dialogInfo.cu = 0
        })
      }
    },
    // * 审核通过 ： 正审
    async handlesubmitCU() {
      const res = await this.$http.post('advpgmlist/reviewadvseq', {
        pl_id: this.pgmgrpnode.key, review_word: this.reviewform.review_word, review_status: 1
      })
      if (res.status !== 200) {
        this.errorMessage('审核失败!')
      }
      this.playDialog = { status: 0 }// 关闭弹窗
      this.pgmgrpCurr.status = 0 // 审核状态设为已通过
      return this.$message.success('审核成功!')
    },
    // * 审核不通过 ： 反审
    async handlesubmitNO() {
      const res = await this.$http.post('advpgmlist/reviewadvseq', {
        pl_id: this.pgmgrpnode.key, review_word: this.reviewform.review_word, review_status: 2
      })
      if (res.status !== 200) {
        this.errorMessage('审核失败!')
      }
      this.playDialog = { status: 0 }// 关闭弹窗
      this.pgmgrpCurr.status = 1 // 审核状态设为未通过
      return this.$message.success('审核成功!')
    },
    handlecancelCU() {
      this.playDialog = { status: 0 }// 关闭弹窗
    },
    async deletePgmgrp() {
      const confirmresult = await this.$confirm('是否删除广告节目单`' + this.pgmgrpCurr.label + '` ，是否确定？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('您已取消了删除')
      }
      const ids = [this.pgmgrpCurr.value]
      channelGroupDel(ids).then(res => {
        if (res.data.data.code !== 1) {
          return this.errorMessage('删除失败')
        }
        this.$message.success('删除成功')
        this.getmatTypeList()
        this.defaultKeys = [this.pgmgrpCurr.pid]
      })
    },
    async historyData() {
      channelGroup({ type: 'all' }).then(res => {
        if (res.status !== 200) {
          console.log('频道分组获取失败')
        }
        this.optionsType[0].children = res.data.data
      })
    },
    async ReviewDetail() {
      //* this.resetPlayForm(this.rowscurrent.pgm_id)
      this.playDialog = { status: 1 }// 打开弹窗
    },
    async delgrpDetail() {
      if (this.handleCheckboxRows.length < 1) {
        return this.$alert('请至少选中一条节目！', '', {
          confirmButtonText: '确定',
          type: 'error',
          callback: function() {

          }
        })
      }
      const confirmresult = await this.$confirm('是否删除当前选中广告节目单`' + this.pgmgrpCurr.label + '` 下节目信息 ，是否确定？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('您已取消了删除')
      }

      const newData = this.handleCheckboxRows.filter(item => { // 获取当前广告节目单中选中的节目单
        return item
      })

      const matid_str = newData.map(item => {
        return item.id
      }).join()

      const data = {
        id: matid_str
      }

      del(data).then(res => {
        if (res.status !== 200) return
        this.grplistSave = false
        this.$notify({
          title: '删除成功',
          message: '节目删除成功！',
          type: 'success'
        })
        this.getgrpDetail()
      })
    },
    // 监听table列表多选checkbox多选变化事件
    handleSelectionChange(select) {
      this.handleCheckboxRows = select || []
    }
  }
}
</script>

<style lang="less">
  .animat {
    i {
      color: #0086B3;
    }
    animation: aname .8s 5;
  }
  .el-form-item {
    margin-bottom: 3px !important;
  }
  .operator {
    float: right;
    display: inline-block;
    margin-left: 20px;
  }
  .detailOpera .el-button {
    margin-top: 15px;
  }
  .leftBox {
    height: 81vh;
    background-color: rgba(222, 223, 230, 0.6);
  }
  .footCard {
    border:  1px solid rgba(222, 223, 230, 1);
    margin-top: 10px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
  }
  .empty_type {
    color: #f00 ! important;
  }
  .el-select-dropdown__item.selected{
    font-weight: normal;
  }
  .another-row{
    background: #f3efde !important;
  }
  #floatmousebox {
    position: fixed;
  }
</style>
